var grid = null;//表格对象
var manger;
var manger2;
var dataType = null; //数据类型
var typeid = null;//配置分类ID
var treeManger = null;
var editor;
/*
 * 初始化加载
 */
$(function(){
	typeLisTab();
	editor = UE.getEditor('editor'); 
	$("#addValue").click(function(e) { addConfValue(); });
	$("#editValue").click(function(e) { editConfValue(); });
	$("#btnDelValue").click(function(e) { delConfValue(); });
	
});
 /* =============配置分类       */
/**
 * 配置类型列表
 * @param url 请求数据地址
 */
function typeLisTab(id){
	var url = _path+"/conf/typelist";
	$.ajax( {
		url : url,
		type : "POST",
		async : false,
		dataType : "json",
		success : function(result) {
			if(result.msg=="success"){
				var array = result.Rows;
				var html = new Array();
				var j = 0;
				for ( var i = 0; i < array.length; i++) {
					html.push('<a id="conf'+array[i].id+'" href="javascript:show(\''+array[i].id+'\',\''+array[i].type+'\',\''+array[i].delsubflag+'\')" class="list-group-item">');
					html.push('<i class="fa fa-home"></i>&nbsp;'+array[i].confname);
					html.push('<div class="btn-group btn-group-xs" style="float: right">');
					html.push('<button type="button" class="btn btn-warning" onclick="editConf(\''+array[i].id+'\',\''+array[i].confname+'\',\''+array[i].type+'\',\''+array[i].remark+'\',\''+array[i].sort+'\',\''+array[i].level+'\',\''+array[i].delsubflag+'\')"><i class="fa fa-cog"></i></button>');
					// luzhirui 2015-09-17临时改造，只有系统管理员才有权限删除配置项
					if ("superadmin" == _username) {
						html.push('&nbsp;<button type="button" class="btn btn-danger" onclick="delConf(\''+array[i].id+'\',\''+array[i].confname+'\')"><i class="fa fa-trash-o"></i></button>');
					}
					html.push('</div></a>');
					if(id && id==array[i].id)
						j = i;
				}
				$("#typegrid").html(html.join(''));
				show(array[j].id,array[j].type,array[j].delsubflag);
			}
		}
	});
     $("#pageloading").hide();
}

/**
 * 根据类型 展示不同的 配置项信息
 * @param id
 * @param type
 */
function show(id,type,delsubflag) {
	if (delsubflag == "1") {
		$("#btnDelValue").hide();
	} else {
		$("#btnDelValue").show();
	}
	$("#conf"+id).siblings().removeClass("active");
	$("#conf"+id).addClass("active");
	var url = _path+"/conf/infolist/"+id;
	dataType = type;
	typeid = id;
	if(type == 0){//树
		iniTreeTab(url);
	}else if(type == 1){//列表
		initInfoTab(url);
	}else if(type == 2){//kv文字模式
		initKVTab(url);
	}else if(type == 3){//kv编辑器模式
		initKVEditTab(url);
	}
}

/**
 * 添加配置分类
 */
function addConf() {
	var baseInfo = $("#confbaseInfo");
	baseInfo.find("input:not(:radio)").val('');
	baseInfo.find("input:radio[value='1']").attr("checked", "checked");
	baseInfo.find("#btnDel").hide();
	baseInfo.modal('show');
	
}

/**
 * 保存配置项
 */
function saveConf() {
	App.ajax(_path+"/conf/saveType", $("#confformBase").serialize(), function(data) {
		switch(data.statusCode) {
		case 200 : App.bubble(data.statusCode, "保存成功！"); typeLisTab(data.id); $("#confbaseInfo").modal('hide'); break;
		case 500 : App.bubble(data.statusCode, data.msg); break;
		default : App.bubble(500, "操作失败！"); break;
		}
	});
}

/**
 * 编辑分类
 * @param id
 * @param confname
 * @param type
 * @param remark
 * @param sort
 */
function editConf(id,confname,type,remark,sort,level,delsubflag){
	var baseInfo = $("#confbaseInfo");
	baseInfo.find("#id").val(id);
	baseInfo.find("#confname").val(confname);
	baseInfo.find("#type").val(type);
	baseInfo.find("#level").val(level);
	baseInfo.find("#delsubflag").val(delsubflag);
	baseInfo.find("#sort").val(sort);
	baseInfo.find("#remark").val(conver(remark));
	$("#confbaseInfo").modal('show');

}
function delConf(id,confname) {
	if(window.confirm("确认删除配置分类："+confname+"?"))
		App.ajax(_path+"/conf/deleteType?id="+id, '', function(data) {
			switch(data.statusCode) {
			case 200 : App.bubble(data.statusCode, "删除成功！"); typeLisTab(); $("#confbaseInfo").modal('hide'); break;
			case 500 : App.bubble(data.statusCode, data.msg); break;
			default : App.bubble(500, "操作失败！"); break;
			}
		});
	return false;
}		


/* =============配置项值信息       */

/**
 * 配置内容：列表模式
 * @param url
 */
function initInfoTab(url){
	$("#listgrid").hide();
	$("#listgrid2").show();
	var pageSize=20;
	manger2 = $("#listgrid2").ligerGrid({
		width:'98%',
		height:'93%',
		headerRowHeight:36,
		rowHeight:36,
		checkbox: true,
		columns: [
					{ display: 'id', name: 'id', width: '13%' },
					{ display: '备注/(签收单位)ip开始', name: 'remark',  width: '30%' },
					{ display: '文字', name: 'value0',  width: '15%' },
					{ display: '链接/(签收单位)ip结束', name: 'value1',  width: '30%' },
					{ display: '图片', name: 'value2',  width: '10%' ,render:function (row){
					if(!isNull(row.value2)){
							return '<img style="height:35px;width:60px" src="'+row.value2+'"/>';
						}else{
							return row.value2;
						}
		            }},
		          { display: '顺序', name: 'sort',  width: '5%' },
		          { display: '扩展1', name: 'value3',  width: '10%' },
		          { display: '扩展2', name: 'value4',  width: '10%' }
		          ], url:url, pageSize:20,rownumbers:true,pageParmName:"curNo",pagesizeParmName:"curSize"
		        	 
	});
	$("#pageloading").hide();
}

/**
 * 配置内容：键值对 文本模式
 * @param url
 */
function initKVTab(url){
	$("#listgrid").hide();
	$("#listgrid2").show();
	var pageSize=20;
	manger2 = $("#listgrid2").ligerGrid({
		width:'98%',
		height:'93%',
		headerRowHeight:36,
		rowHeight:36,
		checkbox: true,
		columns: [
		          { display: '标识', name: 'id', width: '15%' },
		          { display: '配置值', name: 'value0',  width: '35%' },
		          { display: '备注', name: 'remark',  width: '40%' }
		         ], url:url, pageSize:20,rownumbers:true,pageParmName:"curNo",pagesizeParmName:"curSize"
		        	 
	});
	$("#pageloading").hide();
}


/**
 * 配置内容：键值对 图文模式
 * @param url
 */
function initKVEditTab(url){
	$("#listgrid").hide();
	$("#listgrid2").show();
	var pageSize=20;
	manger2 = $("#listgrid2").ligerGrid({
		width:'98%',
		height:'93%',
		headerRowHeight:36,
		rowHeight:36,
		checkbox: true,
		columns: [
		          { display: '标识', name: 'id', width: '15%' },
		          { display: '备注', name: 'remark',  width: '30%' },
		          { display: '内容', name: 'value0',  width: '40%' ,render:function (row){
					return '<button type="button" class="btn btn-warning" onclick="editConfValueById('+row.id+')"><i class="fa fa-cog"></i></button>';
		          }}
		         ], url:url, pageSize:20,rownumbers:true,pageParmName:"curNo",pagesizeParmName:"curSize"
		        	 
	});
	$("#pageloading").hide();
}

/**
 * 配置信息树形列表
 * @param url
 */
function iniTreeTab(url){
	$("#listgrid2").hide();
	$("#listgrid").show();
	if(manger!=null){
		manger.options.url = url;
		manger.reload();
	}else{
	manger = $("#listgrid").ligerGrid({
         columns: [
         { display: 'id', name: 'id', width: '0%' ,hide:true},
         { display: 'pid', name: 'pid', width: '0%' ,hide:true},
         { display: '分类名称', name: 'value0', width: '20%', align: 'left' },
         { display: '分类标识id', name: 'id', width: '15%' },
         { display: '链接', name: 'value1', width: '15%', align: 'left' },
         { display: '图片', name: 'value2',  width: '10%' ,render:function (row){
				if(!isNull(row.value2)){
						return '<img style="height:35px;width:60px" src="'+row.value2+'"/>';
					}else{
						return row.value2;
					}
	            }},
         { display: '顺序', name: 'sort',  width: '5%' },
         { display: '备注', name: 'remark', width: '20%', align: 'left' },
         { display: '扩展1', name: 'value3',  width: '10%' },
         { display: '扩展2', name: 'value4',  width: '10%' }
         ], width: '98%', height: '93%',
         url: url, alternatingRow: false,usePager:false, tree: {
        	 columnName: 'value0',
        	 idField: 'id',
             parentIDField: 'pid'
         },onAfterShowData:function(){
        	 manger.collapseAll();
         }
     });
	}
}	
 
/**
 * 添加配置内容
 */	
function addConfValue() {
	var baseInfo = null;
	if(dataType == 0){//树
		var url = _path+"/conf/infolist/"+typeid;
		initTree(url);
		baseInfo = $("#confvaluebaseInfo");
		baseInfo.find("#pic").html(passPicHtml(''));
	}else if(dataType == 1){//列表
		baseInfo = $("#confvaluebaseInfo2");
		baseInfo.find("#pic").html(passPicHtml('2'));
	}else if(dataType == 2){//kv文字模式
		baseInfo = $("#confvaluebaseInfo3");
	}else if(dataType == 3){//kv编辑器模式
		baseInfo = $("#confvaluebaseInfo4");
	}
	
	editorContent = ''
	editorready();
	 
	baseInfo.find("input:not(:radio)").val('');
	baseInfo.find("textarea").val('');
	
	baseInfo.find("input:radio[value='1']").attr("checked", "checked");
	baseInfo.find("#btnDel").hide();
	baseInfo.find("#typeid").val(typeid);

	baseInfo.modal('show');
	
}

//typeLisTab(data.id); 
var baseDiv = null;

var filename = null;
function saveValue() {
	if(dataType == 0){
		baseDiv = $("#confvaluebaseInfo");
		filename ='file';
		ajaxFileUpload(saveConfValue);
	}else if(dataType == 1){
		baseDiv = $("#confvaluebaseInfo2");
		filename ='file2';
		ajaxFileUpload(saveConfValue);
	}else if(dataType == 2){
		baseDiv = $("#confvaluebaseInfo3");
		saveConfValue();
	}else if(dataType == 3){
		baseDiv = $("#confvaluebaseInfo4");
		var context = editor.getContent();
        if (!/[\w\W]+/.test(context)) {
            alert("内容不能为空");
            return;
        }
        $("#confvaluebaseInfo4 #value0").val(context);
        saveConfValue();
	}
}

function saveConfValue() {
	var fromParamData = baseDiv.find("#confvalueformBase").serialize();
	App.ajax(_path+"/conf/save", fromParamData, function(data) {
		switch(data.statusCode) {
		case 200 : App.bubble(data.statusCode, "保存成功！");show(typeid,dataType);baseDiv.modal('hide'); break;
		case 500 : App.bubble(data.statusCode, data.msg); break;
		default : App.bubble(500, "操作失败！"); break;
		}
	});
}

/**
 * 图片上传
 * @param callback
 * @returns {Boolean}
 */
function ajaxFileUpload(callback) {	
	$("#loading").ajaxStart(function(){
		$(this).show();
	}).ajaxComplete(function(){
		$(this).hide();
	});
	if ($("#"+filename).val() !== "") {
		$.ajaxFileUpload({
			url: _path+'/conf/upload', 
			secureuri: false,
			fileElementId: filename,
			dataType: 'json',
			success: function (data, status) {
				switch(data.statusCode) {
				case 200 : baseDiv.find("#value2").val(data.uri); callback(); break;
					case 500 : App.bubble(500, data.info);  break;
					}
				}
			});
		return false;
	} else{
		callback();
	}
}

/**
 * 图文模式 按id查看配置内容
 * @param rowid
 */
function editConfValueById(rowid){
	var baseInfo = null;
	baseInfo = $("#confvaluebaseInfo4");
	App.ajax(_path+"/conf/queryById", "id="+rowid, function(data) {
		baseInfo.find("#id").val(data.dataList.id);
		baseInfo.find("#pid").val(data.dataList.pid);
		baseInfo.find("#typeid").val(data.dataList.typeid);
		baseInfo.find("#value0").val(data.dataList.value0);
		baseInfo.find("#remark").val(data.dataList.remark);
		baseInfo.modal('show');
		if(dataType == 0){
			var url = _path+"/conf/infolist/"+typeid;
			initTree(url);
		}else if(dataType == 3){
			editor.reset();
			editorContent = data.dataList.value0
			editorready();
		}
	});
}

/**
 * 生成图片上传html
 * @param index
 * @returns
 */
function passPicHtml(index){
	var html = new Array();
	html.push('<label class="col-md-3 control-label">图片</label>');
	html.push('<div class="col-md-8"><div class="fileinput fileinput-new" data-provides="fileinput">');
	html.push( '<div class="fileinput-new thumbnail" style="width: 300px; height: 100px;"><img class="delpic" id="showImg"></div>');
	html.push('<div class="fileinput-preview fileinput-exists thumbnail imgdel" style="max-width: 200px; max-height: 100px;"></div>');
	html.push('<div><span class="btn default btn-file"><span class="fileinput-new">上传图片</span>');
	html.push('<span class="fileinput-exists">修改</span><input type="file" id="file'+index+'" accept="image/*" name="file" /></span>');
	html.push('<a href="#" onclick="delpic();" class="btn default fileinput-exists" data-dismiss="fileinput">删除</a><a href="#" onclick="delpic();" class="btn default fileinput-new" data-dismiss="fileinput">删除</a></div></div></div>');
	
	return html.join('');
}

/**
 * 删除编辑默认图片
 */
function delpic(){
	$("input[name='value2']").val("");
	$(".delpic").attr("src","");
}

/**
 * 编辑配置项
 */
function editConfValue(){
	var baseInfo = null;
	var rowid= null;//获取选中记录行
	if(dataType == 0){
		baseInfo = $("#confvaluebaseInfo");
		baseInfo.find("#pic").html(passPicHtml(''));
		rowid=manger.getSelecteds();
	}else if(dataType == 1){
		baseInfo = $("#confvaluebaseInfo2");
		baseInfo.find("#pic").html(passPicHtml('2'));
		rowid=manger2.getSelecteds();
	}else if(dataType == 2){
		baseInfo = $("#confvaluebaseInfo3");
		rowid=manger2.getSelecteds();
	}else if(dataType == 3){
		baseInfo = $("#confvaluebaseInfo4");
		rowid=manger2.getSelecteds();
	}
	
	baseInfo.find("input:not(:radio)").val('');

	baseInfo.find("input:radio[value='1']").attr("checked", "checked");
	baseInfo.find("#btnDel").hide();
	baseInfo.find("#typeid").val(typeid);
	
	var length=rowid.length;
	if(length ==0){
		App.bubble(500, "请选择需要修改的配置项！");
		return false;
	}
	if(length == 1){
		App.ajax(_path+"/conf/queryById", "id="+rowid[0].id, function(data) {
			baseInfo.find("#id").val(data.dataList.id);
			baseInfo.find("#pid").val(data.dataList.pid);
			baseInfo.find("#typeid").val(data.dataList.typeid);
			baseInfo.find("#keywords").val(data.dataList.keywords);
			baseInfo.find("#value0").val(data.dataList.value0);
			baseInfo.find("#value1").val(data.dataList.value1);
			baseInfo.find("#value2").val(data.dataList.value2);
			baseInfo.find("#remark").val(data.dataList.remark);
			baseInfo.find("#showImg").attr("src",data.dataList.value2);
			baseInfo.find("#levels").val(data.dataList.levels);
			baseInfo.find("#sort").val(data.dataList.sort);
			baseInfo.find("#value3").val(data.dataList.value3);
			baseInfo.find("#value4").val(data.dataList.value4);

			baseInfo.modal('show');
			if(dataType == 0){
				var url = _path+"/conf/infolist/"+typeid;
				initTree(url);
			}else if(dataType == 3){
				editor.reset();
				editorContent = data.dataList.value0
				editorready();
			}
		});
	}else{
		App.bubble(500, "只能选择一个配置项进行修改配置项！");
	}
}

/**
 * 编辑器 初始化之后 设置内容
 */
var editorContent = '';
function editorready(){
	editor.addListener("ready", function () {
		editor.setContent(editorContent);
 });
}

function delConfValue() {
	var baseInfo = null;
	var rowid= null;//获取选中记录行
	if(dataType == 0){
		baseInfo = $("#confvaluebaseInfo");
		rowid=manger.getSelecteds();
	}else{
		baseInfo = $("#confvaluebaseInfo2");
		rowid=manger2.getSelecteds();
	}
	
	var length=rowid.length;
	if(length ==0){
		App.bubble(500, "请选择删除的配置项！");
		return false;
	}
	
	if(window.confirm("确认删除选中配置项?")) {
        var ids = new Array();
        for(var i=0, len=rowid.length; i<len; i++) {
            ids.push(rowid[i].id);
        }
        App.ajax(_path+"/conf/delete", {"ids": ids}, function(data) {
            switch(data.statusCode) {
                case 200 : App.bubble(data.statusCode, "删除成功！"); show(typeid,dataType); baseInfo.modal('hide'); break;
                case 500 : App.bubble(data.statusCode, data.msg); break;
                default : App.bubble(500, "请操作失败！"); break;
            }
        });
    }
	return false;
}
	

  
/**
 * @title : 以树的形式展示机构
 * */
function initTree(url){
	$.ajax({
		type:"post",
		url: url,
		async : false,
		success:function(data){
			var treeData = [];
			treeData.push( {
				'id' : '0',
				'icon' : '',
				'text' : '配置树',
				'isexpand' : true,
				'pid' : ""
			});
			var orgList = data.Rows;
			for(var i=0;i<orgList.length;i++){
				treeData.push( {
					'id' : orgList[i].id,
					'icon' : '',
					'text' : orgList[i].value0,
					'isexpand' : false,
					'pid' : orgList[i].pid
				});
			}
			loadTree(treeData);
		}
	});
}

//加载树
function loadTree(dataTree) {
	var $$ = $("#dataTree");
	$$.html("<div style='height: 300px;overflow-y: auto'></div>");
	treeManger = $$.children().ligerTree( {
		data : dataTree,
		idFieldName : 'id',
		parentIDFieldName : 'pid',
		checkbox : false,
		slide : true,
		nodeWidth :160,
		onSelect : onSelect
	});
	var baseInfo = $("#confvaluebaseInfo");
	var nodeId = baseInfo.find("#pid").val();
	if(nodeId!='-1' && nodeId!=''){
		var data = treeManger.getDataByID(nodeId);
		onclickPass(data);
		treeManger.selectNode(nodeId);
	}
}
function onSelect(note){
	onclickPass(note.data);
}
function onclickPass(data){
	var baseInfo = $("#confvaluebaseInfo");
	var valueId = data.id;
	var pvalue = data.text;
	if(valueId == "-1"){
		baseInfo.find("#pid").val("999999");
		baseInfo.find("#pvalue").val("机构列表");
	}else{
		baseInfo.find("#pid").val(valueId);
		baseInfo.find("#pvalue").val(pvalue) ;
	}
}
 
